<?php

class HomeController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public function index()
	{
		// return View::make('index');
		/*if (Auth::check()) {
			return Redirect::to('/multi-product-ads');
		}
		return Redirect::to('/login');*/
		return View::make('home');
	}

	function multiProductAds() {
		$expried = DB::table('users')->select(DB::raw('expried_time - NOW() AS exp, expried_time, trial_remain'))->where('id', Auth::user()->id)->first();
		
		return View::make('multiproductads')
		->with('pages', Fbpage::where('user_id', Auth::user()->id)->get())
		->with('expried', $expried)
		->with('input', Input::old());
	}
	function processMultiProductAds() {
		$files = Input::file('productimage');
		$todayFolder = date('Ymd');
		$uploadFolder = public_path() . '/uploads/' . $todayFolder . '/';
		// $arrExt = array('jpg', 'png', 'gif', 'jpeg');
		$arrExt = Config::get('app.allowedExt');
		$dataImg = [];
		$childAttachments = [];
		$i = 0;
		foreach( $files as $file) {
			$randomName = uniqid();
			if(empty($file)) continue;
			$extension = strtolower($file->getClientOriginalExtension());
			if (!in_array($extension, $arrExt)) {
				continue;
			}
			$file->move($uploadFolder, $randomName . '.' . $extension);
			array_push($dataImg, array('file_path' => '/uploads/' . $todayFolder . '/' . $randomName . '.' . $extension, 'user_id' => Auth::user()->id, 'created_at' => date('Y-m-d H:i:s')));
			array_push($childAttachments, array(
				'link' => Input::get('linkimg')[$i],
				'name' => Input::get('titleimage')[$i],
				'description' => Input::get('descimg')[$i],
				'picture' => URL::to('/uploads/' . $todayFolder . '/' . $randomName . '.' . $extension),
				));

			$i++;
		}
		if (count($dataImg) >= 3) {
			//Image::insert($dataImg);
			// preparing for Multi Product Ads API
			$pageId = Input::get('fbpage');
			$params['message'] = Input::get('message');
			$params['published'] = '0';
			$params['child_attachments'] = json_encode($childAttachments);
			$params['caption'] = Input::get('caption');
			$params['link'] = Input::get('link');
			// get page access token
			$page = Fbpage::select('page_token', 'page_name')->where('user_id', Auth::user()->id)->where('fb_page_id', $pageId)->first();
			$apiUrl = 'https://graph.facebook.com/v2.2/' . $pageId . '/feed?access_token=' . $page->page_token;
			$response = json_decode($this->curl($apiUrl, $params), true);

			$pagepost = new Pagepost;
			$pagepost->rawdata = json_encode($response);
			if (isset($response['error']['message'])) {
				$pagepost->error = $response['error']['message'];
			}
			if (isset($response['id'])) {
				$pagepost->fb_post_id = $response['id'];
			}
			$pagepost->user_id = Auth::user()->id;
			$pagepost->page_id = $pageId;
			$pagepost->post_type = 'MPA';

			$pagepost->save();
			if( isset($pagepost->error)) {
				return Redirect::back()
				->withInput()
				->with('error', $pagepost->error);
			}
			if( (strtotime(Auth::user()->expried_time) - time()) <= 0) {
				User::where('id', Auth::user()->id)->decrement('trial_remain');
			}
			return Redirect::to('/mpa-final')
			->with('postid', $response['id'])
			->with('pagename', $page->page_name);
		}
		else {
			return Redirect::back()->withInput()->with('error', 'Error when uploading images');
		}
	}
	function mpaFinal() {
		if (!Session::get('postid')) {
			return Redirect::to('/multi-product-ads');
		}
		return View::make('mpa-final');
	}
	public static function curl($url, $params = []){
		try{
			// create a new cURL resource
			$ch = curl_init();

			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_USERAGENT, ' Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0');
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// require to get data from https
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($ch, CURLOPT_TIMEOUT, 1800);
			curl_setopt($ch, CURLOPT_AUTOREFERER, true);
			if (!empty($params)) {
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
			}
			$data = curl_exec($ch);
			curl_close($ch);
			return $data;
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
		return null;
	}
	public function pricing() {
		return View::make('pricing');
	}
	public function payment() {
		// prevent resubmit the form
		Session::put('_token', sha1(microtime()));

		$package = Input::get('package');
		$quantity = intval(Input::get('quantity'));
		$packages = Config::get('app.packages');
		if (!array_key_exists($package, $packages)) {
			return Redirect::to('/pricing');
		}
		$orderCode = strtoupper('FT'.self::unique_id(5));
		$pakageDetail = $packages[$package]['title'];
		$price = $packages[$package]['price'];
		$totalAmount = $price * $quantity;

		$order = new Order;
		$order->order_code = $orderCode;
		$order->user_id = Auth::user()->id;
		$order->order_package = $package;
		$order->save();

		return View::make('payment')
		->with('orderCode', $orderCode)
		->with('quantity', $quantity)
		->with('pakageDetail', $pakageDetail)
		->with('price', $price)
		->with('package', $package)
		->with('totalAmount', $totalAmount);
	}

	function unique_id($l = 8) {
	    return substr(md5(uniqid(mt_rand(), true)), 0, $l);
	}

	function pageNotifications() {
		$pages = Fbpage::where('user_id', Auth::user()->id)->get();
		$data = Fbpage::getPagesNotifications($pages);
		$arrData = [];
		$notifications = [];
		$summary = [];
		$i = 0;

		foreach ($data as $pageNoti) {
			if(!isset($pageNoti['body'])) {
				continue;
			}
			$notifications = json_decode($pageNoti['body'], true);
			if(!isset($notifications['error'])) {
				array_push($arrData, array(
					'page_info' => array(
						'fb_page_id' => $pages[$i]['fb_page_id'],
						'page_name' => $pages[$i]['page_name']
					),
					'unread' => isset($notifications['summary']) ? $notifications['summary']['unseen_count'] : 0,
					'notifications' => $notifications['data']
				));

				$i++;
			}
		}
		return Response::json($arrData);
	}
	function contactus() {
		$msg = date('d/m/Y H:i') . "\n" . Input::get('name') . "\n" . Input::get('email') . "\n" . Input::get('message') . "\n=====================================\n";
		file_put_contents(base_path() . '/contact.txt', $msg, FILE_APPEND);
		echo 'Cảm ơn bạn đã gửi thông tin liên hệ, chúng tôi đã nhận được thông tin và phản hồi lại cho bạn ngay khi có thể.';
		exit(0);
	}
}
